package b1.conifg.story
{
	import flash.accessibility.Accessibility;
	
	public class TowerLayerConfig
	{
		private const distMax:int = 99999;
		private const directX:Array = [1, -1, 0, 0];
		private const directY:Array = [0, 0, 1, -1];
		public var mapRows:Array;
		public var mapGrids:Array;
		
		public function TowerLayerConfig(layerXML:XML)
		{
			var rowNum:int = layerXML.mapRow.length();
			mapRows = new Array(rowNum);
			var mapGrid:TowerGridConfig;
			for (var i:int = 0; i < rowNum; i++)
			{
				var mapRowStrs:Array = layerXML.mapRow[i].split(",");
				mapRows[i] = new Array(mapRowStrs.length);
				for (var j:int = 0; j < mapRowStrs.length; j++)
				{
					mapGrid = new TowerGridConfig();
					mapGrid.posX = i;
					mapGrid.posY = j;
					var mapGridStrs:Array = mapRowStrs[j].split("/");
					mapGrid.texture = parseInt(mapGridStrs[0]);
					mapGrid.type = parseInt(mapGridStrs[1]);
					mapRows[i][j] = mapGrid;
				}
			}
			var gridNum:int = layerXML.mapGrid.length();
			mapGrids = new Array();
			for (i = 0; i < gridNum; i++)
			{
				mapGrid = new TowerGridConfig(layerXML.mapGrid[i]);
				mapRows[mapGrid.posX][mapGrid.posY] = mapGrid;
				mapGrids.push(mapGrid);
			}
		}
		
		public function findPath(startX:int, startY:int, stopX:int, stopY:int):Array
		{
			for (var i:int = 0; i < mapRows.length; i++)
			{
				for (var j:int = 0; j < mapRows[i].length; j++)
				{
					mapRows[i][j].dist = distMax;
				}
			}
			var head:int = 0;
			var queue:Array = new Array();
			mapRows[startX][startY].dist = 0;
			queue.push(mapRows[startX][startY]);
			var currentGrid:TowerGridConfig;
			while (head < queue.length)
			{
				currentGrid = queue[head];
				//到达目的
				if (currentGrid.posX == stopX && currentGrid.posY == stopY)
					break;
				for (var d:int = 0; d < 4; d++)
				{
					var neighborX:int = currentGrid.posX + directX[d];
					var neighborY:int = currentGrid.posY + directY[d];
					if (neighborX >= 0 && neighborY >= 0 && neighborX < mapRows.length && neighborY < mapRows[neighborX].length)
					{
						var neighborGrid:TowerGridConfig = mapRows[neighborX][neighborY];
						if (currentGrid.dist + 1 < neighborGrid.dist && (neighborGrid.type == 0 || neighborGrid.keyId > 0 || neighborGrid.lockId > 0 ||
							neighborGrid.exitLiveId != 0 || neighborGrid.nextLayerId != 0))
						{
							neighborGrid.dist = currentGrid.dist + 1;
							neighborGrid.parent = currentGrid;
							queue.push(neighborGrid);
						}
					}
				}
				head++;
			}
			var path:Array = new Array();
			if (currentGrid != null && currentGrid.posX == stopX && currentGrid.posY == stopY)
			{
				while (!(currentGrid.posX == startX && currentGrid.posY == startY))
				{
					path.push(currentGrid);
					currentGrid = currentGrid.parent;
				}
			}
			return path;
		}

	}
}